package game.module.qzmj.processor;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.module.init.logic.RoomConnectManager;
import game.module.qzmj.bean.QzmjRound;
import game.module.qzmj.logic.QzmjDatamanager;
import game.module.qzmj.logic.QzmjLogic;
import game.module.user.dao.LanSessionCache;
import lion.common.MsgCodeAnn;
import lion.netty4.message.GamePlayer;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lion.netty4.processor.MsgProcessor;
import lua.LuaMessageQzmj.C2SQzmjConnectRoom;
import lua.LuaMessageQzmj.S2CQzmjConnectRoom;

@MsgCodeAnn(msgcode = C2SQzmjConnectRoom.id,accessLimit = 500)
public class QzmjRoomServerConnectProcessor extends MsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(QzmjRoomServerConnectProcessor.class);

	@Override
	public void process(GamePlayer gamePlayer, RequestMessageRaw request) throws Exception {
		// TODO Auto-generated method stub
		C2SQzmjConnectRoom reqMsg = C2SQzmjConnectRoom.parse(request);
		long roomSessionId = reqMsg.sessionId;
		Integer playerId = LanSessionCache.getInstance().getCachePlayerId(roomSessionId);
		logger.info("qzmj room connect,sessionId={},player={}", roomSessionId,playerId);
		if (playerId == null) {
			S2CQzmjConnectRoom retMsg = new S2CQzmjConnectRoom(1);
			gamePlayer.writeAndFlush(retMsg.build(gamePlayer.alloc()));
			return;
		}
		// 创建玩家
		RoomConnectManager.cacheNewPlayer(roomSessionId, gamePlayer, playerId);
		S2CQzmjConnectRoom retMsg = new S2CQzmjConnectRoom(0);
		gamePlayer.writeAndFlush(retMsg.build(gamePlayer.alloc()));
		//将进入房间的玩家放入对局信息中
		QzmjRound mjRound = QzmjDatamanager.getInstance().getMjRoom(playerId);
		
		synchronized (mjRound) {
			QzmjLogic mjlogic = QzmjLogic.getInstance();
			//logger.info("Mj room connect,sessionId={}",mjRound );
			Set<Integer> enter_player = mjRound.getEnter_player();
			enter_player.add(playerId);
			logger.info("qzmj room connect,room munber={},enter_player={}",enter_player.size(),enter_player);
			if(enter_player.size()==4){
				logger.info("qz mj  start ");
				mjlogic.GameStart(mjRound); //当四个人都连接上房间服务器后，系统开始自动摇色子和自动补花和金牌的确定
			}
		}
	}

	@Override
	public void process(GamePlayer session, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void process(GamePlayer player, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	
}
